<?php

namespace app\api\controller;

use app\common\controller\Wxpay;
use app\common\controller\Wxpay2;
use app\common\controller\WxPayService;
use app\common\model\Help;
use app\common\model\Wechat;
use think\Request;
use library\Controller;
use think\Db;
use think\App;

class Index extends Controller
{
    //小程序登录
    public $header;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $help = new Help();
        $this->header = $help->em_getallheaders();
    }

    //微信小程序充值
    public function charge()
    {
        $wechat = new Wechat();
        $_W = $wechat->mini_config($this->header);

        $data['user_id'] = 1;
        $data['amount'] = 0.01;
        $member = Db::table("store_member")->where(["id" => $data['user_id']])->find();
        $data['before'] = $member['amount'];
        $data['after'] = $member['amount']+$data['amount'];
        $data['memo'] = '余额充值';
        $data['out_trade_no'] = date('YmdHis') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
        $data['create_at'] = date('Y-m-d H:i:s');
        $data['lx'] = 0;
        $data['insert_id'] = Db::table("store_member_amount_log")->insertGetId($data);

        $body = '微信支付';

        $appid = $_W['app_id'];
        $openid = $member['openid']; //oQKgL0ZKHwzAY-KhiyEEAsakW5Zg
        $mch_id = $_W['mchid'];
        $key = $_W['wxkey'];
        $out_trade_no = $data['out_trade_no'];
        $total_fee = $data['amount'];
        $root = sysconf('realm_name') . '/index.php/api/index/charge_notify';

        if (empty($total_fee)) //押金
        {
            $total_fee = floatval(99 * 100);
        } else {
            $total_fee = floatval($total_fee * 100);
        }

        //$total_fee = 1;
        $weixinpay = new Wxpay($appid, $openid, $mch_id, $key, $out_trade_no, $body, $total_fee, $root);
        $return = $weixinpay->pay();

        echo json_encode(['code'=>200,'data'=>$return,'msg'=>'请求成功']);
    }

    //App充值
    public function charge_app(){

        //uniapp的  "appid" : "__UNI__B7636D0",  包名 uni.UNIB7636D0, 和微信开放平台的appid  wx0e2a450b8c9ddb8c，包名 uni.UNIB7636D0  完全一致  才能支付，
        //目前 GLUZ 有例子  哈哈哈哈

        try {
            $wxPay = new WxPayService();

            // 创建支付订单
            $orderParams = [
                'out_trade_no' => date('YmdHis') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT), // 商户订单号
                'total_fee'    => 100, // 转为分
                'body'         => 'APP支付',
            ];

            $result = $wxPay->unifiedOrder($orderParams);

            echo json_encode([
                'code' => 200,
                'msg'  => 'success',
                'data' => $result
            ]);

        } catch (\Exception $e) {
            echo json_encode([
                'code' => 500,
                'msg'  => $e->getMessage()
            ]);
        }
    }



    //充值回调
    public function charge_notify(){
        $xml = file_get_contents('php://input');
        $arr = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);

        if ($arr) {
            if ($arr['result_code'] == 'SUCCESS') {
                $out_trade_no = trim($arr['out_trade_no']);

                Db::table('store_member_amount_log')->where(array('out_trade_no' => $out_trade_no))->update(['is_pay' => 1, 'pay_no' => $arr['transaction_id'], 'pay_time' => date('Y-m-d H:i:s')]);

                $find = Db::table('store_member_amount_log')->where(array('out_trade_no' => $out_trade_no))->find();

                Db::table("store_member")->where(array('id' => $find['user_id']))->update(['amount'=> $find['after'] ]);
            }
        }

        $return = array('return_code' => 'SUCCESS', 'return_msg' => 'OK');
        $xml = '<xml>';
        foreach ($return as $k => $v) {
            $xml .= '<' . $k . '><![CDATA[' . $v . ']]></' . $k . '>';
        }
        $xml .= '</xml>';

        echo $xml;
        exit;
    }

}